package com.winning.ds.role.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.winning.ds.common.dao.CommonApiDao;
import com.winning.ds.common.entity.*;
import com.winning.ds.common.util.UUIDUtils;
import com.winning.ds.role.dao.SysUserDao;
import com.winning.ds.role.entity.*;
import com.winning.ds.role.entity.*;
import com.winning.ds.role.service.SysUserService;
import com.winning.jcpt.sdk.sm4.SM4Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @program: plat
 * @description:
 * @author: nxs
 * @create: 2018-07-05 09:34
 */
@Service("SysUserService")
public class SysUserServiceImpl implements SysUserService {
  @Autowired private SysUserDao sysUserDao;

  @Autowired private CommonApiDao commonApiDao;

  @Override
  @Transactional
  public SysUserEntity queryByUserName(String username) {
    return sysUserDao.queryByUserName(username);
  }

  @Override
  @Transactional
  public SysUserEntity selectByUserName(String username) {
    return sysUserDao.selectByUserName(username);
  }

  @Override
  @Transactional
  public CommonJgUserEntity queryUserObject(String zclsh) {
    CommonJgUserEntity us = commonApiDao.queryUserObject(zclsh);

    int login_error_count = 0;
    SysQjcsEntity lecEntity = commonApiDao.queryQjcs("login_error_count");
    if (lecEntity != null && StringUtils.isNotEmpty(lecEntity.getCsz())) {
      login_error_count = Integer.parseInt(lecEntity.getCsz());
    }
    // 确定锁定参数配置锁定次数大于0
    if (login_error_count > 0) {
      // 当失败次数大于参数最大失败次数时，前台传值为0：锁定，否则传1：正常
      if (us != null && StringUtils.isNotEmpty(us.getSbcs())) {
        int cs = Integer.parseInt(us.getSbcs());
        if (cs < login_error_count) {
          us.setSbcs("1");
        } else {
          us.setSbcs("0");
        }
      }
    } else {
      us.setSbcs("1");
    }

    return us;
  }

  @Override
  @Transactional
  public void save(SysUserEntity user) {
    sysUserDao.insert(user);
  }

  @Override
  @Transactional
  public void update(SysUserEntity user) {
    sysUserDao.updateUser(user);
  }

  @Override
  @Transactional
  public List<SysUserEntity> queryList(Map<String, String> queryParams) {
    List<SysUserEntity> list = sysUserDao.queryList(queryParams);
    return list;
  }

  @Override
  @Transactional
  public List<YhryxxEntity> yhryList(Map<String, Object> queryParams) {
    List<YhryxxEntity> list = sysUserDao.yhryList(queryParams);
    return list;
  }

  @Override
  @Transactional
  public List queryZwDic() {
    List<SysSjyzymlEntity> list = sysUserDao.queryZwDic();
    return list;
  }

  @Override
  public void deleteUser(String zclsh) {
    sysUserDao.deleteUser(zclsh);
  }

  // 查询机构科室信息
  @Override
  @Transactional
  public List queryKsxx(String jgdm) {
    List list = sysUserDao.queryKsxx(jgdm);
    return list;
  }

  // 保存用户角色
  @Override
  @Transactional
  public void saveUserRole(Map userRole) {
    sysUserDao.saveUserRole(userRole);
  }

  // 查询用户角色信息
  @Override
  @Transactional
  public List getUserRole(String zclsh) {
    return sysUserDao.getUserRole(zclsh);
  }

  // 批量导入用户
  @Override
  @Transactional
  public void pldrYh(List<SysUserEntity> userList) {
    for (SysUserEntity user : userList) {
      sysUserDao.pldrYh(user);
    }
  }

  // 删除用户角色信息
  @Override
  @Transactional
  public void delUserRole(String zclsh) {
    sysUserDao.delUserRole(zclsh);
  }

  // 查询菜单树
  @Override
  public List<MenuTreeEntity> getQxList(String zclsh) {
    return sysUserDao.getQxList(zclsh);
  }

  // 查询当前机构开通的菜单权限
  @Override
  public List<MenuTreeEntity> getMenuByJgbm(String jgbm) {
    return sysUserDao.getMenuByJgbm(jgbm);
  }

  // 查询权限用户列表
  @Override
  public List<SysUserEntity> queryQxyhList(Map<String, Object> queryParams) {
    return sysUserDao.queryQxyhList(queryParams);
  }

  @Override
  public String getMaxDldm(String dldm) {
    return sysUserDao.getMaxDldm(dldm);
  }

  @Override
  public SysUserEntity queryUserEntity(String zclsh) {
    return commonApiDao.queryUserEntity(zclsh);
  }

  @Override
  public void saveUserRoleList(List<Map> czry, List<Map> jsxx) {
    if (czry != null && czry.size() > 0) {
      for (int i = 0; i < czry.size(); i++) {
        Map parm = new HashMap();
        Map us = czry.get(i);
        // 先删除该用户的角色信息
        sysUserDao.delUserRole(us.get("zclsh").toString());
        parm.put("jgbm", us.get("jgbm"));
        parm.put("zclsh", us.get("zclsh"));

        if (jsxx != null && jsxx.size() > 0) {
          for (int j = 0; j < jsxx.size(); j++) {
            parm.put("lsh", UUIDUtils.getUUID());
            parm.put("jsdm", jsxx.get(j).get("jsdm"));
            sysUserDao.saveUserRole(parm);
          }
        }
      }
    }
  }

  // 根据qzsql 查询 参数
  @Override
  public List<Map<String, Object>> getOptionList(String qzsql) {
    List<Map<String, Object>> list = new ArrayList<>();
    try {
      if (org.apache.commons.lang.StringUtils.isNotEmpty(qzsql)) {
        list = sysUserDao.getOptionList(qzsql);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return list;
  }

  /** 北京对接国家平台获取第三方目标系统中“账号”等对象全部属性信息 */
  @Override
  public BjGjptSchemaResponseEntity schemaService(BjGjptUserRequestEntity bjGjptUserRequestEntity) {
    BjGjptSchemaResponseEntity responseEntity = new BjGjptSchemaResponseEntity();
    List<BjGjptAccount> account = new ArrayList<>();
    BjGjptAccount bjGjptAccount1 = new BjGjptAccount();
    bjGjptAccount1.setName("organizationId");
    bjGjptAccount1.setMultivalued("false");
    bjGjptAccount1.setRequired("true");
    bjGjptAccount1.setType("String");
    account.add(bjGjptAccount1);
    BjGjptAccount bjGjptAccount2 = new BjGjptAccount();
    bjGjptAccount2.setName("organizationName");
    bjGjptAccount2.setMultivalued("false");
    bjGjptAccount2.setRequired("true");
    bjGjptAccount2.setType("String");
    account.add(bjGjptAccount2);
    BjGjptAccount bjGjptAccount3 = new BjGjptAccount();
    bjGjptAccount3.setName("loginName");
    bjGjptAccount3.setMultivalued("false");
    bjGjptAccount3.setRequired("true");
    bjGjptAccount3.setType("String");
    account.add(bjGjptAccount3);
    BjGjptAccount bjGjptAccount4 = new BjGjptAccount();
    bjGjptAccount4.setName("fullName");
    bjGjptAccount4.setMultivalued("false");
    bjGjptAccount4.setRequired("true");
    bjGjptAccount4.setType("String");
    account.add(bjGjptAccount4);
    BjGjptAccount bjGjptAccount5 = new BjGjptAccount();
    bjGjptAccount5.setName("IDCard");
    bjGjptAccount5.setMultivalued("false");
    bjGjptAccount5.setRequired("false");
    bjGjptAccount5.setType("String");
    account.add(bjGjptAccount5);
    BjGjptAccount bjGjptAccount6 = new BjGjptAccount();
    bjGjptAccount6.setName("mobile");
    bjGjptAccount6.setMultivalued("false");
    bjGjptAccount6.setRequired("false");
    bjGjptAccount6.setType("String");
    account.add(bjGjptAccount6);
    BjGjptAccount bjGjptAccount7 = new BjGjptAccount();
    bjGjptAccount7.setName("sex");
    bjGjptAccount7.setMultivalued("false");
    bjGjptAccount7.setRequired("false");
    bjGjptAccount7.setType("String");
    account.add(bjGjptAccount7);
    responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
    responseEntity.setAccount(account);
    return responseEntity;
  }
  /** 北京对接国家平台应用系统的账号创建方法 */
  @Override
  @Transactional
  public BjGjptUserResponseEntity userCreateService(
      BjGjptUserRequestEntity bjGjptUserRequestEntity) {
    BjGjptUserResponseEntity responseEntity = new BjGjptUserResponseEntity();
    String lshUid = "";
    if (bjGjptUserRequestEntity == null
        && StringUtils.isEmpty(bjGjptUserRequestEntity.getLoginName())
        && StringUtils.isEmpty(bjGjptUserRequestEntity.getFullName())
        && StringUtils.isEmpty(bjGjptUserRequestEntity.getBimRequestId())) {
      responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
      responseEntity.setResultCode("500");
      responseEntity.setMessage("字段不全，账号创建失败");
      return responseEntity;
    }
    SysUserEntity user = sysUserDao.selectByUserName(bjGjptUserRequestEntity.getLoginName());
    if (user != null) {
      responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
      responseEntity.setResultCode("509");
      responseEntity.setMessage("登录账号已存在，账号创建失败");
      return responseEntity;
    }
    try {
      SysQjcsEntity lecEntity = commonApiDao.queryQjcs("bj_uams_jgbm");
      String jgbm = "";
      if (lecEntity != null) {
        jgbm = lecEntity.getCsz();
      }
      SysUserEntity userEntity = new SysUserEntity();
      String password = "1"; // 默认密码为1
      SM4Utils sm4Utils = new SM4Utils();
      userEntity.setDlmm(password); // 保存密码（明文）
      password = sm4Utils.encryptData_CBC(password); // 采用对称的加密
      userEntity.setPassword(password);
      lshUid = UUIDUtils.getUUID();
      userEntity.setJgbm(jgbm);
      userEntity.setZclsh(lshUid);
      userEntity.setRybm(lshUid);
      userEntity.setDldm(bjGjptUserRequestEntity.getLoginName());
      userEntity.setRygh(bjGjptUserRequestEntity.getLoginName());
      userEntity.setQyzt("Y");
      userEntity.setRyxm(bjGjptUserRequestEntity.getFullName());
      userEntity.setSfzh(
          bjGjptUserRequestEntity.getIDCard() == null ? "" : bjGjptUserRequestEntity.getIDCard());
      userEntity.setDhhm(
          bjGjptUserRequestEntity.getMobile() == null ? "" : bjGjptUserRequestEntity.getMobile());
      userEntity.setXb(
          bjGjptUserRequestEntity.getSex() == null ? "" : bjGjptUserRequestEntity.getSex());
      userEntity.setJlzt("0");
      userEntity.setMmxgsj(new Date());
      sysUserDao.insert(userEntity);
      Map parm = new HashMap();
      parm.put("jgbm", "WN");
      parm.put("zclsh", lshUid);
      parm.put("lsh", UUIDUtils.getUUID());
      parm.put("jsdm", "748ceb166b674b9d8d9f56ec4b701142");
      sysUserDao.saveUserRole(parm);
      responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
      responseEntity.setResultCode("0");
      responseEntity.setMessage("success");
      responseEntity.setUid(lshUid);
    } catch (Exception e) {
      responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
      responseEntity.setResultCode("501");
      responseEntity.setMessage("保存失败");
      return responseEntity;
    }
    return responseEntity;
  }
  /** 北京对接国家平台应用系统的账号修改方法 */
  @Override
  public BjGjptUserResponseEntity userUpdateService(
      BjGjptUserRequestEntity bjGjptUserRequestEntity) {
    BjGjptUserResponseEntity responseEntity = new BjGjptUserResponseEntity();
    if (bjGjptUserRequestEntity == null
        && StringUtils.isEmpty(bjGjptUserRequestEntity.getBimUid())
        && StringUtils.isEmpty(bjGjptUserRequestEntity.getFullName())
        && StringUtils.isEmpty(bjGjptUserRequestEntity.getBimRequestId())) {
      responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
      responseEntity.setResultCode("500");
      responseEntity.setMessage("字段不全，账号创建失败");
      return responseEntity;
    }

    try {
      SysUserEntity sysUserEntity =
          commonApiDao.queryUserEntity(bjGjptUserRequestEntity.getBimUid());
      if (sysUserEntity != null) { // 修改
        sysUserEntity.setRyxm(bjGjptUserRequestEntity.getFullName());
        // sysUserEntity.setDldm(bjGjptUserRequestEntity.getLoginName());
        sysUserEntity.setSfzh(
            bjGjptUserRequestEntity.getIDCard() == null ? "" : bjGjptUserRequestEntity.getIDCard());
        sysUserEntity.setDhhm(
            bjGjptUserRequestEntity.getMobile() == null ? "" : bjGjptUserRequestEntity.getMobile());
        sysUserEntity.setXb(
            bjGjptUserRequestEntity.getSex() == null ? "" : bjGjptUserRequestEntity.getSex());
        sysUserDao.updateUser(sysUserEntity);
        responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
        responseEntity.setResultCode("0");
        responseEntity.setMessage("success");
      } else {
        responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
        responseEntity.setResultCode("502");
        responseEntity.setMessage("修改失败,用户不存在");
        return responseEntity;
      }
    } catch (Exception e) {
      responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
      responseEntity.setResultCode("503");
      responseEntity.setMessage("修改失败");
      return responseEntity;
    }
    return responseEntity;
  }
  /** 北京对接国家平台应用系统的账号删除方法。 */
  @Override
  public BjGjptUserResponseEntity userDeleteService(
      BjGjptUserRequestEntity bjGjptUserRequestEntity) {
    BjGjptUserResponseEntity responseEntity = new BjGjptUserResponseEntity();
    if (bjGjptUserRequestEntity == null
        && StringUtils.isEmpty(bjGjptUserRequestEntity.getBimUid())
        && StringUtils.isEmpty(bjGjptUserRequestEntity.getBimRequestId())) {
      responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
      responseEntity.setResultCode("500");
      responseEntity.setMessage("字段不全，账号创建失败");
      return responseEntity;
    }
    try {
      SysUserEntity sysUserEntity =
          commonApiDao.queryUserEntity(bjGjptUserRequestEntity.getBimUid());
      if (sysUserEntity != null) { // 修改
        sysUserDao.deleteUser(bjGjptUserRequestEntity.getBimUid());
        responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
        responseEntity.setResultCode("0");
        responseEntity.setMessage("success");
      } else {
        responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
        responseEntity.setResultCode("504");
        responseEntity.setMessage("删除失败,用户不存在");
        return responseEntity;
      }
    } catch (Exception e) {
      responseEntity.setBimRequestId(bjGjptUserRequestEntity.getBimRequestId());
      responseEntity.setResultCode("505");
      responseEntity.setMessage("删除失败");
      return responseEntity;
    }
    return responseEntity;
  }
  /** 查询用户映射列表 */
  @Override
  public List<PtLoginsEntity> queryUserMappingList(Map<String, String> queryParams) {
    List<PtLoginsEntity> list = sysUserDao.queryUserMappingList(queryParams);
    return list;
  }
  /** 保存用户映射关系 */
  @Override
  public void saveUserMapping(Map<String, String> queryParams) {
    Map params = new HashMap();
    params.put("userid", queryParams.get("userid"));
    params.put("systemid", queryParams.get("systemid"));
    List<PtLoginsEntity> list = sysUserDao.queryUserMappingList(params);
    if (list != null && list.size() > 0) {
      sysUserDao.updateUserMapping(queryParams);
    } else {
      sysUserDao.insertUserMapping(queryParams);
    }
  }
  /** 删除用户映射关系 */
  @Override
  public void delUserMapping(Map<String, String> queryParams) {
    sysUserDao.delUserMapping(queryParams);
  }
}
